<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use cmf\controller\HomeBaseController;
use app\portal\model\PortalCategoryModel;
use app\portal\service\PostService;
use app\portal\model\PortalPostModel;
use app\portal\model\PortalTagModel;
use think\db\Where;

class SearchController extends HomeBaseController
{
    /**
     * 搜索
     * @return mixed
     */
    public function index()
    {
        $keyword = $this->request->param('keyword');
        if (empty($keyword)) {
            $this -> error("关键词不能为空！请重新输入！");
        }

        $pageSize = 15;
        $words = $this->autoWord($keyword);


        $PortalTagModel = new PortalTagModel();
        $PortalPostModel = new PortalPostModel();
        //相关标签
        $relateTagData = $PortalTagModel->relatedTagLists($words,1,20);

        //分页问题已解决
        $data =  $PortalPostModel->getSearchLists($words,$pageSize);

        $pages = $data->render();
        $data =json_decode(json_encode($data),true);
        $total = $data['total'];


        $routeData = $PortalPostModel->getRouteData();
        $result = $PortalPostModel->getRealUrlLists($data['data'],$routeData);

        $tagLists = $PortalTagModel->articleTagLists(array_column($result,'id'));
        foreach($result as $k=>&$v){
            $v['taglist'] = isset($tagLists[$v['id']]) ? $tagLists[$v['id']] : [];
        }

        $this->assign("keyword", $keyword);
        $this->assign("pages", $pages);
        $this->assign("data", $result);
        $this->assign("relateTagData", $relateTagData);
        $this->assign("total", $total);
        return $this->fetch('/search');
    }
}
